const API_BASE_URL = 'http://localhost:3000/api';

export interface Log {
  no: number;
  uuid: string;
  name: string;
}

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

// 获取所有日志
export const getAllLogs = async (): Promise<ApiResponse<Log[]>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/logs`);
    return await response.json();
  } catch (error) {
    return {
      success: false,
      message: '获取日志失败',
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
};

// 根据 ID 获取日志
export const getLogById = async (no: number): Promise<ApiResponse<Log>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/logs/${no}`);
    return await response.json();
  } catch (error) {
    return {
      success: false,
      message: '获取日志失败',
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
};

// 创建新日志
export const createLog = async (logData: Omit<Log, 'no'>): Promise<ApiResponse<Log>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/logs`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(logData),
    });
    return await response.json();
  } catch (error) {
    return {
      success: false,
      message: '创建日志失败',
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
};

// 更新日志
export const updateLog = async (no: number, logData: Omit<Log, 'no'>): Promise<ApiResponse<Log>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/logs/${no}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(logData),
    });
    return await response.json();
  } catch (error) {
    return {
      success: false,
      message: '更新日志失败',
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
};

// 删除日志
export const deleteLog = async (no: number): Promise<ApiResponse<void>> => {
  try {
    const response = await fetch(`${API_BASE_URL}/logs/${no}`, {
      method: 'DELETE',
    });
    return await response.json();
  } catch (error) {
    return {
      success: false,
      message: '删除日志失败',
      error: error instanceof Error ? error.message : '未知错误'
    };
  }
}; 